package com.lc.pianostudent.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Picture;
import android.os.Looper;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.lc.pianostudent.BaseApplication;
import com.zcx.helper.util.UtilToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2018/8/1.
 */

public class PictureUpload {

    String endpoint = "http://oss-cn-beijing.aliyuncs.com/";
    String url = "http://qinzhiyu.oss-cn-beijing.aliyuncs.com/";
    //填写明文accessKeyId和accessKeySecret，加密官网有
    OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAIbFwEcaDiCHR2", "XHDLoIRBCS0rc2BRUxTrcsydmpe4q7");

    private static PictureUpload pictureUpload;


    private Activity activity;
    /**
     * 上传client
     */
    OSS oss;
    /**
     * 上传次数
     */


    private int position;
    /**
     * 成功上传(本地文件名作为key,阿里云地址为value)
     */
    List<String> success = new ArrayList<>();
    /**
     * 失败上传(返回失败文件的本地地址)
     */
    List<String> failure = new ArrayList<>();
    /**
     * 上传回调
     */
    UploadListener uploadListener;


    List<String> paths;
    /**
     * 上传任务列表
     */
    //List<OSSAsyncTask> ossAsyncTasks = new ArrayList<>();
    /**
     * 自动更新Token
     */
    /*OSSCredentialProvider credetialProvider = new OSSFederationCredentialProvider() {
        @Override
        public OSSFederationToken getFederationToken() {
            try {
                //阿里鉴权请求
                AliAuthRes res = new JsonDefaultRequest(AliAuthRes.class).POST("", null, SharePerefrence.getTokenKey());
                return new OSSFederationToken(res.getAccessKeyId(), res.getAccessKeySecret(), res.getSecurityToken(), res.getExpiration());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    };*/

    /**
     * 单列模式
     *
     * @return
     */
    public static PictureUpload getInstance(Activity activity) {
        if (pictureUpload == null) {
            pictureUpload = new PictureUpload(activity);
        }
        return pictureUpload;
    }

    /**
     * 构造函数
     */
    public PictureUpload(Activity activity) {

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(20 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(20 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(9); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(3); // 失败后最大重试次数，默认2次
        oss = new OSSClient(BaseApplication.getContext(), endpoint, credentialProvider, conf);
        this.activity =activity;
    }

    /**
     * 添加上传任务
     *
     * @param paths
     * @param listener
     */
    public void setDatas(int position,List<String> paths, UploadListener listener) {
        this.paths =paths;
        this.position =position;
        this.uploadListener = listener;
        //ossAsyncTasks.clear();

        success.clear();
        failure.clear();
        if (paths!=null&&paths.size()>0){
            String path =paths.get(0).toString();
            String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());//文件名称
            upLoad(1,fileName,path);

        }else {
            listener.onUploadComplete(position,success,failure);
        }


    }



    private void  upLoad(final int positions, final String fileName, final String path){
        PutObjectRequest put = new PutObjectRequest("qinzhiyu", fileName, path);
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest putObjectRequest, long currentSize, long totalSize) {

            }
        });
        /**
         * 上传任务
         */

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(final PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        String aliPath = url+fileName;
                        success.add(aliPath);
                        if (positions == paths.size()) {
                            uploadListener.onUploadComplete(position,success, failure);
                        }else {
                            if(paths.size() != 0){
                                String s = paths.get(positions).toString();
                                String photoName = s.substring(s.lastIndexOf("/") + 1, s.length());//文件名称
                                upLoad(positions+1,photoName,s);//继续上传
                            }


                        }


                    }
                });



            }

            @Override
            public void onFailure(final PutObjectRequest putObjectRequest, ClientException clientExcepion, ServiceException serviceException) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        failure.add("");
                        if (positions == paths.size()) {
                            uploadListener.onUploadComplete(position,success, failure);
                        }else {
                            String s = paths.get(positions).toString();
                            String photoName = s.substring(s.lastIndexOf("/") + 1, s.length());//文件名称
                            upLoad(positions+1,photoName,s);//继续上传

                        }


                    }
                });

                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    UtilToast.show("服务器异常");
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });




    }



}
